package com.buer.storage.controller;

import com.buer.storage.commom.JsonResult;
import com.buer.storage.dto.LoginDTO;
import com.buer.storage.entity.UserEntity;
import com.buer.storage.entity.UserEntityDO;
import com.buer.storage.service.AuthService;
import com.buer.storage.utils.Result;
import com.buer.storage.vo.TokenVO;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验
 */
@RestController("/")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    /**
     * 登录
     *
     * @param loginDTO
     * @return token登录凭证
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO loginDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.build(400, bindingResult.getFieldError().getDefaultMessage());
        }
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        //用户信息
        UserEntityDO user = authService.findByUsername(username);
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(password)) {
            return Result.build(400, "用户名或密码错误");
        } else {
            //生成token，并保存到数据库
            String token = authService.createToken(user);
            TokenVO tokenVO = new TokenVO();
            tokenVO.setUsername(username);
            tokenVO.setToken(token);
            return Result.ok(tokenVO);
        }
    }

}